import Cookies from 'js-cookie'
import { paramsMap } from '@/router/menu'

const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  cachedViews: [],
  device: 'desktop',
  rawMenu: null,
  menuChildren: [],
  item: null,
  hasDemoRoutes:true, 
}

const mutations = {
  TOGGLE_SIDEBAR: (state, isopen) => {
    if (typeof isopen == 'undefined') {
      state.sidebar.opened = !state.sidebar.opened
    } else {
      state.sidebar.opened = !!isopen
    }
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SET_MENU_CHILDREN: (state, { item, children }) => {
    state.item = item
    state.menuChildren = children
  },
  SET_CACHED_VIEWS: (state, cachedViews) => {
    state.cachedViews = cachedViews
  },
  SET_RAW_MENU: (state, rawMenu) => {
    state.rawMenu = rawMenu
  }
}

const actions = {
  toggleSideBar({ commit }, isopen) {
    commit('TOGGLE_SIDEBAR', isopen)
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setMenuChildren({ commit }, { item, children }) {
    commit('SET_MENU_CHILDREN', { item, children })

    commit('TOGGLE_SIDEBAR', !!children.length)
  },
  setCachedViews({ commit, state }) {
    commit('SET_CACHED_VIEWS', [])
    setTimeout(() => {
      let menu = []
      if (state.rawMenu) {
        menu = state.rawMenu
      }
      const cachedViews = menu.filter(d => d[paramsMap.metaMap.cache]).map(d => d[paramsMap.map.name]) 
      commit('SET_CACHED_VIEWS', cachedViews)
    },100)
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
